//
//  ViewController.swift
//  sss
//
//  Created by 周旗 on 2025/4/29.
//

import UIKit
import ARKit

class ViewController: UIViewController, ARSCNViewDelegate {
    @IBOutlet weak var sceneView: ARSCNView!
    
    // 轨迹参数
    let movementThreshold: Float = 0.1
    let pointsPerMeter: CGFloat = 20  // 1m -> 1cm 屏幕映射（38 pt ≈ 1 cm）

    // 状态变量
    var originWorld: SIMD2<Float>?
    var lastWorldPos: SIMD2<Float>?
    var mapOrigin: CGPoint = .zero
    var mapPoints = [CGPoint]()

    // UI 元素
    let mapLayer = CAShapeLayer()
    
    let personImageView: UIImageView = {
        let iv = UIImageView(image: UIImage(named: "person_icon"))
        iv.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
        return iv
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        sceneView.delegate = self
        setUpUI()
    }
    
    

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let config = ARWorldTrackingConfiguration()
        sceneView.session.run(config)
    }

    func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
        guard let frame = sceneView.session.currentFrame else { return }
        let t = frame.camera.transform
        let worldPos = t.columns.3 // 获取完整的平移向量
        let worldXZ = SIMD2<Float>(worldPos.x, worldPos.z) // x和z坐标

        if originWorld == nil {
            originWorld = worldXZ
            mapOrigin = CGPoint(x: mapLayer.bounds.midX, y: mapLayer.bounds.midY)
            mapPoints = [mapOrigin]
            lastWorldPos = worldXZ
            return
        }
        
        DispatchQueue.main.async {
            self.updateTowards()
        }
        guard let last = lastWorldPos else { return }
        // 判断两点距离是否超过预想的距离 0.1
        guard simd_distance(worldXZ, last) > movementThreshold else { return }

        lastWorldPos = worldXZ

        // 计算相对于原点的位移
        let deltaX = worldXZ.x - originWorld!.x
        let deltaZ = worldXZ.y - originWorld!.y
        let dx = CGFloat(deltaX) * pointsPerMeter
        let dz = CGFloat(deltaZ) * pointsPerMeter
        
        // 调整Y轴方向：AR的Z正向对应地图的Y正向
        let newMapPoint = CGPoint(x: mapOrigin.x + dx, y: mapOrigin.y + dz)
        mapPoints.append(newMapPoint)

        DispatchQueue.main.async {
            self.redrawMapPath()
        }
    }
     // 绘制行走路径
    func redrawMapPath() {
        guard mapPoints.count >= 2 else { return }

        // 绘制路径折线
        let path = UIBezierPath()
        path.move(to: mapPoints[0])
        for point in mapPoints.dropFirst() {
            path.addLine(to: point)
        }
        mapLayer.path = path.cgPath
    }
    
    // 更新小人头像位置和朝向
    func updateTowards(){
        guard mapPoints.count >= 2 else { return }
        let last = mapPoints[mapPoints.count - 1]
        let prev = mapPoints[mapPoints.count - 2]

        personImageView.center = last

        let dx = last.x - prev.x
        let dy = last.y - prev.y
        let angle = atan2(dy, dx)

        personImageView.transform = CGAffineTransform(rotationAngle: angle)
    }
}

extension ViewController {
    func setUpUI() {
        // 配置地图 overlay
        let mapView = UIView(frame: CGRect(
            x: 0,
            y: 0,
            width: UIScreen.main.bounds.width,
            height: UIScreen.main.bounds.height))
        mapView.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        mapView.layer.cornerRadius = 8
        mapView.clipsToBounds = true
        sceneView.addSubview(mapView)

        // 配置路径 layer
        mapLayer.strokeColor = UIColor.green.cgColor
        mapLayer.fillColor = UIColor.clear.cgColor
        mapLayer.lineWidth = 6
        mapLayer.frame = mapView.bounds
        mapView.layer.addSublayer(mapLayer)

        // 添加小人图标
        mapView.addSubview(personImageView)
        personImageView.center = mapView.center
    }
}
